package xin.nick.common.handler;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.NoHandlerFoundException;
import xin.nick.common.constant.SystemConstants;
import xin.nick.common.entity.Result;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author Nick
 * @since 2022/7/21/021
 */
// @Controller
public class ErrorControllerImpl implements ErrorController {

    // RestControllerAdvice 拦不到的错误， 我来拦
    // 然后再丢给 RestControllerAdvice
    // 拦的太多了..... 2022年7月21日21:31:48

    @RequestMapping("/error")
    public Result handleError(HttpServletRequest request) throws Throwable {


        // 判断是 servlet 异常的情况下，抛出异常，让全局异常捕捉
        Object attribute = request.getAttribute(SystemConstants.SERVLET_ERROR_EXCEPTION);
        if (Objects.nonNull(attribute)) {
            throw (Throwable) attribute;
        }
        HttpStatus status = this.getStatus(request);

        if (status == HttpStatus.NOT_FOUND) {
            throw new NoHandlerFoundException(request.getMethod(), request.getRequestURL().toString(), null);
        }

        throw new RuntimeException("filter层的异常");
    }

    protected HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer)request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        } else {
            try {
                return HttpStatus.valueOf(statusCode);
            } catch (Exception var4) {
                return HttpStatus.INTERNAL_SERVER_ERROR;
            }
        }
    }
}
